package com.dlc.shop.distribution.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.vo.DistributionConfigVO;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.i18n.I18nMessage;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.distribution.api.param.DistributionWithdrawCashSaceParam;
import com.dlc.shop.distribution.common.constants.DistributionUserStateEnum;
import com.dlc.shop.distribution.common.dto.DistributionWithdrawCashDto;
import com.dlc.shop.distribution.common.dto.DistributionWithdrawCashSetDto;
import com.dlc.shop.distribution.common.model.DistributionUser;
import com.dlc.shop.distribution.common.param.RangeTimeParam;
import com.dlc.shop.distribution.common.service.DistributionUserService;
import com.dlc.shop.distribution.common.service.DistributionUserWalletService;
import com.dlc.shop.distribution.common.service.DistributionWithdrawCashService;
import com.dlc.shop.security.api.util.SecurityUtils;
import com.dlc.shop.security.common.enums.SocialType;
import com.dlc.shop.security.common.model.AppConnect;
import com.dlc.shop.security.common.service.AppConnectService;
import com.dlc.shop.service.SysConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author yami
 */
@RestController
@RequestMapping("/p/distribution/withdrawCash")
@Tag(name = "分销员提现接口")
@AllArgsConstructor
public class DistributionWithdrawCashController {
    private final DistributionWithdrawCashService distributionWithdrawCashService;
    private final SysConfigService sysConfigService;
    private final DistributionUserService distributionUserService;

    private final DistributionUserWalletService distributionUserWalletService;
    private final AppConnectService appConnectService;

    @GetMapping("/info")
    @Operation(summary = "获取提现设置信息")
    public ServerResponseEntity<DistributionWithdrawCashSetDto> setInfo() {
        DistributionConfigVO distributionConfigVO = sysConfigService.getSysConfigObject(Constant.DISTRIBUTION_CONFIG, DistributionConfigVO.class);
        return ServerResponseEntity.success(BeanUtil.map(distributionConfigVO, DistributionWithdrawCashSetDto.class));
    }

    @GetMapping("/page")
    @Operation(summary = "分页查看提现记录")
    public ServerResponseEntity<IPage<DistributionWithdrawCashDto>> page(PageParam<DistributionWithdrawCashDto> page) {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(SecurityUtils.getUser().getUserId(), Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            // 您还不是分销员
            throw new YamiShopBindException("yami.distribution.user.no.distributor");
        }
        return ServerResponseEntity.success(distributionWithdrawCashService.distributionWithdrawCashDtoPageByUserId(page, distributionUser.getDistributionUserId()));
    }

    @PostMapping("/apply")
    @Operation(summary = "用户发起提现申请" , description = "填入提现参数")
    public ServerResponseEntity<Void> apply(@Valid @RequestBody DistributionWithdrawCashSaceParam distributionWithdrawCashSaceParam) {
        String userId = SecurityUtils.getUser().getUserId();
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(userId, Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            // 您还不是分销员
            throw new YamiShopBindException("yami.distribution.user.no.distributor");
        }
        if (!Objects.equals(distributionUser.getState(), DistributionUserStateEnum.NORMAL.getValue())){
            // 您的分销身份异常，请联系管理员
            throw new YamiShopBindException("yami.distribution.user.no.distributor1");
        }
        //发起提现
        distributionWithdrawCashService.apply(distributionWithdrawCashSaceParam.getAmount(), distributionUser);
        return ServerResponseEntity.success();
    }

    @GetMapping("/isWithdrawCash")
    @Operation(summary = "当前是否可以提现")
    public ServerResponseEntity<Boolean> isWithdrawCash() {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(SecurityUtils.getUser().getUserId(), Constant.PLATFORM_SHOP_ID);
        Long distributionUserId = distributionUser.getDistributionUserId();
        //获取店铺提现设置
        DistributionConfigVO distributionWithdrawCashSet = sysConfigService.getSysConfigObject(Constant.DISTRIBUTION_CONFIG, DistributionConfigVO.class);
        //获取店铺设置的提现频率算出时间区间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - distributionWithdrawCashSet.getFrequency());
        //获取玩家最近的提现次数
        //判断是否能够提现
        if (distributionWithdrawCashService.getCountByRangeTimeAndDistributionUserId(new RangeTimeParam(calendar.getTime(), new Date()), distributionUserId) >= distributionWithdrawCashSet.getNumber()) {
            // 提现次数为x天x次
            String info = I18nMessage.getMessage("yami.distribution.cash.num");
            String num = I18nMessage.getMessage("yami.constant.num");
            String day = I18nMessage.getMessage("yami.day");
            throw new YamiShopBindException(info + distributionWithdrawCashSet.getFrequency() + day + distributionWithdrawCashSet.getNumber() + num);
        }
        return ServerResponseEntity.success(true);
    }

    @GetMapping("/totalWithdrawCash")
    @Operation(summary = "查看用户总提现金额")
    public ServerResponseEntity<Double> getUserTotalWithdrawCash() {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(SecurityUtils.getUser().getUserId(), Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            // 您还不是分销员
            throw new YamiShopBindException("yami.distribution.user.no.distributor");
        }
        Long distributionUserId = distributionUser.getDistributionUserId();
        Long walletId = distributionUserWalletService.getWalletIdByDistributionUserId(distributionUserId);
        Double totalWithdrawCash = distributionWithdrawCashService.getUserTotalWithdrawCash(walletId);
        return ServerResponseEntity.success(totalWithdrawCash);
    }
}
